package com.sbs.gaoxinqutoilet.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.reflect.TypeToken;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;
import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.adapter.BannerAdapter;
import com.sbs.gaoxinqutoilet.adapter.BaseDelegeteAdapter;
import com.sbs.gaoxinqutoilet.adapter.HomeMenuAdapter;
import com.sbs.gaoxinqutoilet.adapter.HotAdapter;
import com.sbs.gaoxinqutoilet.adapter.SeckillLayoutAdapter;
import com.sbs.gaoxinqutoilet.adapter.StickyTitleAdapter;
import com.sbs.gaoxinqutoilet.base.BaseMainFragment;
import com.sbs.gaoxinqutoilet.entity.GongGaoEntity;
import com.sbs.gaoxinqutoilet.entity.HomeMenuEntity;
import com.sbs.gaoxinqutoilet.entity.HomeNewsEntity;
import com.sbs.gaoxinqutoilet.entity.MainMenuNews;
import com.sbs.gaoxinqutoilet.eventbus.StartNewFragmentEvent;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.Constants;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.JsonUtil;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.SPUtil;
import com.sbs.gaoxinqutoilet.utils.ToastUtils;
import com.sbs.gaoxinqutoilet.utils.loading.LoadingDialog;
import com.sbs.gaoxinqutoilet.view.LoadBottomView;
import com.sunfusheng.marqueeview.MarqueeView;
import com.uuzuche.lib_zxing.DisplayUtil;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import static com.sbs.gaoxinqutoilet.utils.loading.LoadingDialog.cancelLoadingDialog;

/**
 * Created by 聪明一只哈 on 2018/5/30.
 * Time: 2018/5/30  11:24
 */

public class HomeFragment_xiugaione extends BaseMainFragment {


    private TextView toolTitle;
    private ImageView mMenu;
    private AutoLinearLayout toilet_files;
    private AutoLinearLayout toilet_accept;
    private AutoLinearLayout toilet_check;
    private AutoLinearLayout toilet_build;
    private AutoLinearLayout toilet_count;
    private TextView tv_user_name;
    private TextView tv_user_address;
    private HomeMenuRequest homemenuRequest;
    private RecyclerView rv_home;
    private HomeMenuAdapter homeMenuAdapter;

    private View emptyView;
    private View errorView;
    private View footView;
    private List<HomeMenuEntity> homeMenuNewEntities;
    private View view;
    private String token_data;
    private RecyclerView.RecycledViewPool viewPool;

    private MainMenuNews mainMenuNews=new MainMenuNews();
    private VirtualLayoutManager layoutManager;
    private DelegateAdapter delegateAdapter;
    private int itemType;
    private List<DelegateAdapter.Adapter> adapters;
    private MarqueeView marqueeView1;
    private int index=0;
    private int pageSize = 10;
    private TwinklingRefreshLayout tkrefreshLayout;
    private List<HomeNewsEntity.DataBean> news_content;
    private HotAdapter hotAdapter;
    private String recordsTotal;

    public static HomeFragment_xiugaione newInstance() {

        Bundle args = new Bundle();

        HomeFragment_xiugaione fragment = new HomeFragment_xiugaione();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_home_xiugaione, container, false);
        initView(inflater);
        return view;
    }


    /**
     * 初始化view
     *
     * @param inflater
     */
    private void initView(LayoutInflater inflater) {
        //-----------ToolBar初始化------------------------------------------------
        toolTitle = (TextView) view.findViewById(R.id.toolbar_title);
        mMenu = (ImageView) view.findViewById(R.id.toolbar_iv_menu);
//        mMenu.setScaleType(ImageView.ScaleType.FIT_XY);
//        mMenu.setImageResource(R.drawable.shezhi);
        mMenu.setVisibility(View.VISIBLE);

        tkrefreshLayout = view.findViewById(R.id.tkrefresh_layout);


        token_data = SPUtil.getString(Constants.KEY_TOKEN, "");

        toolTitle.setText("高新区农村厕所革命管理系统");
        toolTitle.setTextSize(16f);

        rv_home = (RecyclerView) view.findViewById(R.id.rv_home_list);



        layoutManager = new VirtualLayoutManager(_mActivity);
        layoutManager.setRecycleOffset(300);
        rv_home.setLayoutManager(layoutManager);

        viewPool = new RecyclerView.RecycledViewPool();
        rv_home.setRecycledViewPool(viewPool);
        //itemType为0，目前不存在这个类型的数据
        //viewPool.setMaxRecycledViews(0, 20);

        delegateAdapter = new DelegateAdapter(layoutManager, false);
        rv_home.setAdapter(delegateAdapter);


        //添加刷新头和尾
        SinaRefreshView sinaHeader = new SinaRefreshView(_mActivity);
        sinaHeader.setArrowResource(R.drawable.arrow);
        sinaHeader.setTextColor(0xff745D5C);
        tkrefreshLayout.setHeaderView(sinaHeader);

        //LoadingView loadingView = new LoadingView(_mActivity);
        LoadBottomView loadingView = new LoadBottomView(_mActivity);
        tkrefreshLayout.setBottomView(loadingView);
        //设置是否禁用上下拉
        tkrefreshLayout.setEnableLoadmore(false);
        tkrefreshLayout.setAutoLoadMore(true);




    }


    private void initListener() {

        //menu点击
        mMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().post(new StartNewFragmentEvent(SettingFragment.newInstance()));

            }
        });

        tkrefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            //正在刷新
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                //设置时长
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadMoreData(index,pageSize,false);
                        tkrefreshLayout.finishRefreshing();
                    }
                }, 2000);
            }
            //刷新完成
            @Override
            public void onFinishRefresh() {
                super.onFinishRefresh();
                 LogUtils.i("显示onFinishRefresh", "Finishrefresh");
            }
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadMoreData(index,pageSize,true);
                        tkrefreshLayout.finishLoadmore();
                    }
                }, 1500);
            }
        });
    }

    /**
     * 加载新闻资讯内容数据
     * @param indexs
     * @param pageSize
     */
    private void loadMoreData(int indexs,int pageSize,boolean isLoadMore){

        if(isLoadMore){
            indexs++;
            indexs=indexs*pageSize;
            //新闻内容
            String home_fragment = HttpApis.mian_news;//mian_news_gonggao
            HashMap<String, String> map = new HashMap<>();
            map.put("token",token_data);
            map.put("start", String.valueOf(indexs));
            map.put("pagesize", String.valueOf(pageSize));
            HttpUtils.requestGet(_mActivity, home_fragment, map, new Request(){
                @Override
                public void success(String jsonStr) {
                    super.success(jsonStr);
                    HomeNewsEntity homeNewsEntity = JsonUtil.json2Bean(jsonStr, HomeNewsEntity.class);

                    int totalSize = Integer.parseInt(homeNewsEntity.getRecordsTotal());
                    int listSize = news_content.size();
                    if(listSize>=totalSize){
                        ToastUtils.showShortToast(_mActivity,"加载完毕");
                    }
                    if(homeNewsEntity!=null&&homeNewsEntity.getData()!=null){
                        if(news_content!=null&&news_content.size()>0&&news_content.size()<Integer.parseInt(homeNewsEntity.getRecordsTotal())){


                            news_content.addAll(homeNewsEntity.getData());
                            hotAdapter.notifyDataSetChanged();


                        }
                    }
                }
                @Override
                public void error(String error) {
                    super.error(error);
                }
            });
        }else {
            indexs=0;
            getAllMenuData();
        }

    }

    /**
     * 使用懒加载,加载数据
     * 条目点击监听
     *
     * @param savedInstanceState
     */
    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        initListener();
    }

    /**
     * 动画结束加载
     * 获取主菜单数据
     *
     * @param savedInstanceState
     */
    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        getAllMenuData();
    }


    /**
     * 获取列表数据的所有信息
     */
    private void getAllMenuData() {
        //显示加载对话框
        LoadingDialog.showLoadingDialog(_mActivity);

        String home_fragment = HttpApis.mian_news_img;
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        if (homemenuRequest == null) {
            homemenuRequest = new HomeMenuRequest();
        }
        HttpUtils.requestGet(_mActivity, home_fragment, map, homemenuRequest);

    }

    /**
     * 主列表请求数据
     */
    private class HomeMenuRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);

            HomeNewsEntity homeNewsEntity = JsonUtil.json2Bean(jsonStr, HomeNewsEntity.class);
            if(homeNewsEntity!=null&&homeNewsEntity.getData()!=null){
                mainMenuNews.setBanner_img(homeNewsEntity.getData());
            }

            //主菜单
            String home_fragment = HttpApis.home_fragment;
            HashMap<String, String> map = new HashMap<>();
            map.put("token",token_data);
            HttpUtils.requestGet(_mActivity, home_fragment, map, new Request(){
                @Override
                public void success(String jsonStr) {
                    super.success(jsonStr);
                    LogUtils.i("home", "success: " + jsonStr);
                    Type type = new TypeToken<ArrayList<HomeMenuEntity>>() {
                    }.getType();
                    List<HomeMenuEntity> homeMenuNewEntities = JsonUtil.json2Collection(jsonStr, type);
                    if(homeMenuNewEntities!=null){
                        mainMenuNews.setMenu_data(homeMenuNewEntities);
                        //新闻内容
                        String home_fragment = HttpApis.mian_news;//mian_news_gonggao
                        HashMap<String, String> map = new HashMap<>();
                        map.put("token",token_data);
                        map.put("start", String.valueOf(index));
                        map.put("pagesize", String.valueOf(pageSize));
                        HttpUtils.requestGet(_mActivity, home_fragment, map, new Request(){
                            @Override
                            public void success(String jsonStr) {
                                super.success(jsonStr);
                                HomeNewsEntity homeNewsEntity = JsonUtil.json2Bean(jsonStr, HomeNewsEntity.class);
                                if(homeNewsEntity!=null&&homeNewsEntity.getData()!=null){
                                    mainMenuNews.setNews_content(homeNewsEntity.getData());
                                    recordsTotal = homeNewsEntity.getRecordsTotal();
                                    //新闻公告
                                    String home_fragment = HttpApis.mian_news_gonggao;//mian_news_gonggao
                                    HashMap<String, String> map = new HashMap<>();
                                    map.put("token",token_data);
                                    HttpUtils.requestGet(_mActivity, home_fragment, map, new Request(){
                                        @Override
                                        public void success(String jsonStr) {
                                            super.success(jsonStr);
                                            GongGaoEntity homeNewsEntity = JsonUtil.json2Bean(jsonStr, GongGaoEntity.class);
                                            if(homeNewsEntity!=null&&homeNewsEntity.getData()!=null){
                                                mainMenuNews.setNews_gonggao(homeNewsEntity.getData());
                                                processResultData(mainMenuNews);
                                            }
                                        }
                                        @Override
                                        public void error(String error) {
                                            super.error(error);
                                        }
                                    });
                                }
                            }
                            @Override
                            public void error(String error) {
                                super.error(error);
                            }
                        });
                    }
                }
                @Override
                public void error(String error) {
                    super.error(error);
                }
            });
            cancelLoadingDialog();
        }

        @Override
        public void error(String error) {
            super.error(error);

            cancelLoadingDialog();
        }
    }

    /**
     * 解析数据
     * @param mainMenuNews
     */
    private void processResultData(MainMenuNews mainMenuNews) {
        itemType = 0;
        if (adapters != null) {
            adapters.clear();
        } else {
            adapters = new LinkedList<>();
        }

        //banner
        List<HomeNewsEntity.DataBean> banner_info = mainMenuNews.getBanner_img();
        if (banner_info != null && banner_info.size() > 0) {

            viewPool.setMaxRecycledViews(++itemType, banner_info.size());
            SingleLayoutHelper singleLayoutHelper = new SingleLayoutHelper();//通栏布局，只会显示一个组件View
            singleLayoutHelper.setMargin(0, 0, 0, DisplayUtil.dip2px(_mActivity,8));//设置外边距，实现分割效果
            BannerAdapter bannerAdapter = new BannerAdapter(_mActivity, singleLayoutHelper, banner_info);
            bannerAdapter.setBannerCallback(new BannerAdapter.BannerCallback() {
                @Override
                public void clickBanner(HomeNewsEntity.DataBean itemBean) {
                    //EventBus.getDefault().post(new StartNewFragmentEvent(NewsContentFragment.newInstance(itemBean.getNews_id())));

                }
            });
            adapters.add(bannerAdapter);
        }

        //公告
        List<GongGaoEntity.DataBean> news_gonggao = mainMenuNews.getNews_gonggao();
        if(news_gonggao!=null&&news_gonggao.size()>0){

            SingleLayoutHelper gonggaoLayoutHelper =  new SingleLayoutHelper();//不使用LinearLayoutHelper
            gonggaoLayoutHelper.setMargin(0, 0, 0, DisplayUtil.dip2px(_mActivity,10));//设置外边距，实现分割效果
            BaseDelegeteAdapter gonggaoAdapter = new BaseDelegeteAdapter(_mActivity,gonggaoLayoutHelper,
                    R.layout.vlayout_news, 1){
                @Override
                public void onBindViewHolder(@NonNull BaseViewHolder holder, int i) {
                    marqueeView1 = holder.getView(R.id.marqueeView1);
                    TextView tv_more = holder.getView(R.id.tv_more);

                    List<String> info1 = new ArrayList<>();



                    for (GongGaoEntity.DataBean title : news_gonggao) {
                        String nt_title = title.getNt_title();
                        if(nt_title.length()>=16){
                            nt_title=nt_title.substring(0,16)+"...";
                        }
                        info1.add(nt_title);
                    }

                    if(info1.size()==1){
                        info1.add(info1.get(0));
                    }
                    marqueeView1.startWithList(info1);
                    marqueeView1.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
                        @Override
                        public void onItemClick(int position, TextView textView) {
                            GongGaoEntity.DataBean itemBean = news_gonggao.get(position);
                            EventBus.getDefault().post(new StartNewFragmentEvent(GongGaoFragment.newInstance(itemBean.getNt_id())));
                        }
                    });
                    tv_more.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            EventBus.getDefault().post(new StartNewFragmentEvent(GongGaoListFragment.newInstance(mainMenuNews)));
                        }
                    });
                }
            };
            adapters.add(gonggaoAdapter);

        }


        //Menu
        List<HomeMenuEntity> menuDataList = mainMenuNews.getMenu_data();
        if (menuDataList != null && menuDataList.size() > 0) {

            viewPool.setMaxRecycledViews(++itemType, menuDataList.size());


            SingleLayoutHelper seckillLayoutHelper = new SingleLayoutHelper();//不使用LinearLayoutHelper

            //ChanelAdapter chanelAdapter = new ChanelAdapter(_mActivity, seckillLayoutHelper, menuDataList);
            seckillLayoutHelper.setMargin(0, 0, 0, DisplayUtil.dip2px(_mActivity,10));//设置外边距，实现分割效果

            SeckillLayoutAdapter seckillLayoutAdapter = new SeckillLayoutAdapter(_mActivity, seckillLayoutHelper, menuDataList);

            seckillLayoutAdapter.setHorizontalListCallback(new SeckillLayoutAdapter.HorizontalListCallback() {
                @Override
                public void clickHorizontalItem(HomeMenuEntity itemBean) {

                    switch (itemBean.getFunc_id()) {

                        case "201":
                            //户厕改造档案
                            EventBus.getDefault().post(new StartNewFragmentEvent(ToiletFilesFragment.newInstance(itemBean)));
                            break;

                        case "205":
                            //户厕改造检查  接口暂时没完成 放最后完成
                            EventBus.getDefault().post(new StartNewFragmentEvent(ToiletBuildworkInfoFragment.newInstance(itemBean)));
                            break;


                        case "202":
                            EventBus.getDefault().post(new StartNewFragmentEvent(ToiletBuildAcceptFragment.newInstance(itemBean)));
                            break;

                        case "401":

                            EventBus.getDefault().post(new StartNewFragmentEvent(ToiletBuildCheckFragment.newInstance(itemBean)));
                            break;

                        case "306":
                            EventBus.getDefault().post(new StartNewFragmentEvent(ToiletStatisTicalFragmentD.newInstance(itemBean)));
                            // EventBus.getDefault().post(new StartNewFragmentEvent(ToiletStatisTotalFragment.newInstance(list.get(position))));

                            break;
                        default:

                            break;
                    }

                }
            });

            adapters.add(seckillLayoutAdapter);

        }



        //News
        news_content = mainMenuNews.getNews_content();
        if(news_content !=null&& news_content.size()>0){


            viewPool.setMaxRecycledViews(itemType++, 1);
            SingleLayoutHelper stickyLayoutHelper = new SingleLayoutHelper();
            //stickyLayoutHelper.setMargin(0, 0, 0,  DisplayUtil.dip2px(_mActivity,30));
            StickyTitleAdapter stickyTitleAdapter = new StickyTitleAdapter(_mActivity,stickyLayoutHelper,"最新资讯");
            adapters.add(stickyTitleAdapter);

            viewPool.setMaxRecycledViews(++itemType, news_content.size());
            GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(1);
            gridLayoutHelper.setMargin(0, 0, 0,  DisplayUtil.dip2px(_mActivity,3));
            gridLayoutHelper.setAutoExpand(false);//解决单数的时候，最后一张居中显示的问题
            hotAdapter = new HotAdapter(_mActivity, gridLayoutHelper, news_content);
            hotAdapter.setHotAdapterClicker(new HotAdapter.HotAdapterClicker() {
                @Override
                public void callBack(HomeNewsEntity.DataBean hotInfoBean) {
                    EventBus.getDefault().post(new StartNewFragmentEvent(NewsContentFragment.newInstance(hotInfoBean.getNews_id())));
                }
            });

            adapters.add(hotAdapter);


        }

        delegateAdapter.setAdapters(adapters);

    }

    @Override
    public void onStart() {
        super.onStart();
        if(marqueeView1!=null){
            marqueeView1.startFlipping();
        }

    }

    @Override
    public void onStop() {
        super.onStop();
        if(marqueeView1!=null){
            marqueeView1.stopFlipping();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        OkHttpUtils.getInstance().cancelTag(this);
        cancelLoadingDialog();

    }
}
